/**
 * @date 2014/5/12
 * @author ChenLong
 */
package org.script;


import java.io.FileNotFoundException;
import javax.script.ScriptException;
import org.utils.ExceptionEx;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;

/**
 * 脚本管理类
 */
public class ScriptManager {
    private final static Log log = LogFactory.get(ScriptJavaLoader.class);

    private ScriptManager() {}

    // /**
    // * 初始化脚本管理器
    // *
    // * @param javaPath java脚本所在目录
    // * @param classPath java脚本编译后class所在目录
    // * @param scriptNames 需要加载的脚本集合
    // * @throws FileNotFoundException
    // * @throws ScriptException
    // */
    // public synchronized void initialize(String javaPath, String classPath, Map<Integer, String>
    // scriptNames) throws FileNotFoundException, ScriptException
    // {
    // ScriptJavaLoader.getInstance().initialize(javaPath, classPath);
    // ScriptJavaLoader.getInstance().loadScript(scriptNames);
    // }


    /**
     * 初始化脚本管理器 加载系统指定目录的脚本 scripts/java
     *
     * @param javaPath java脚本所在目录
     * @param classPath java脚本编译后class所在目录
     * @throws FileNotFoundException
     * @throws ScriptException
     */
    public synchronized void initialize(String javaPath, String classPath)
            throws FileNotFoundException, ScriptException {
        ScriptJavaLoader.getInstance().initialize(javaPath, classPath);
        ScriptJavaLoader.getInstance().loadScriptAll();
    }

    /**
     * 调用脚本
     *
     * @param scriptName 脚本全类名
     * @param arg 参数
     * @return
     */
    public Object call(String scriptName, Object arg) {
        try {
            return ScriptJavaLoader.getInstance().call(scriptName, arg);
        } catch (Throwable ex) {
            log.error("call script error! scriptId = " + scriptName + "\n" + ExceptionEx.t2s(ex));
            return null;
        }
    }

    public static ScriptManager getInstance() {
        return Singleton.INSTANCE.getManager();
    }

    private enum Singleton {
        INSTANCE;

        ScriptManager manager;

        Singleton() {
            this.manager = new ScriptManager();
        }

        ScriptManager getManager() {
            return manager;
        }
    }
}
